
import React from 'react';
import Scene from '../components/Scene';
import Sidebar from '../layOut/SideBar';
import Header from '../layOut/Header';
import Footer from '../layOut/Footer';
import { Route } from 'react-router-dom';
import { parseQuery, isFullUrl } from '../utils';
import toast from '../components/Toast/index';
import './style.styl';
// 浏览器跳转
class forwardWithHistory {
    constructor(){
        this.history = '';
    }
    forward = (options, state, method = 'push') => {
        let url = typeof options === 'string' ? options : options.url;
        if (isFullUrl(url)) {
            return (location.href = url);
        }
        this.history[method](url, state);
    };
    setHistory(history) {
        this.history = history;
        this.forward.replace = history.replace;
    }
}

export const forwardFactory =  new forwardWithHistory();

// 后退
export const back = function(history) {
    history.goBack();
};

export const RouteWithSubRoutes = (route) => (
    <Route
        path={route.path}
        exact={true}
        render={props => {
            const { history } = props;
            forwardFactory.setHistory(history);

            const global = {
                forward: forwardFactory.forward,
                back: back.bind(route.component, history),
                toast,
            };

            props.location.query = parseQuery(props.location.search);

            return (
                <React.Fragment>
                    <Header />
                    <div className='app-wrapper'>
                        <Sidebar />
                        <div className='layout-main'>
                            <Scene
                                renderChild={(showError)=> (
                                    <route.component
                                        {...props}
                                        routes={route.routes}
                                        global={{ ...global, showError }}
                                    />
                                )}
                            />
                        </div>
                    </div>
                    <Footer/>
                </React.Fragment>
            );
        }}
    />
);
